package jasepro;

import java.io.DataInputStream;
import java.io.InputStream;
import java.util.StringTokenizer;

public class HttpRequestHdr {
	public String url = new String();
	public String contentType = new String();
	public int contentLength = -1;
	static String CR = "\r\n";
	public String requestString = "";
	private String method = new String();
	private String version = new String();

	public String getMethod() {
		return method;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public boolean parse(InputStream In) {
		String CR = "\r\n";

		DataInputStream lines;
		StringTokenizer tz;
		String tmpLine = "";
		try {
			lines = new DataInputStream(In);
			tmpLine = lines.readLine();
			tz = new StringTokenizer(tmpLine);
		} catch (Exception e) {
			return false;
		}

		method = getToken(tz).toUpperCase();
		url = getToken(tz);
		version = getToken(tz).toUpperCase();

		while (true) {
			try {
				tmpLine = lines.readLine();
				tz = new StringTokenizer(tmpLine);
				requestString += tmpLine + CR;
			} catch (Exception e) {
				System.out.println(e.getMessage());
				return false;
			}
			String token = getToken(tz);

			if (0 == token.length())
				break;

			if (token.equalsIgnoreCase("CONTENT-LENGTH:")) {
				token = getToken(tz);
				contentLength = Integer.parseInt(token);
			} else if (token.equalsIgnoreCase("CONTENT-TYPE:")) {
				contentType = getRemainder(tz);
			}
		}
		return true;
	}

	public String toString() {
		String result = method + " " + url + " " + version + CR + requestString;
		return result;
	}

	String getToken(StringTokenizer tk) {
		String str = "";
		if (tk.hasMoreTokens())
			str = tk.nextToken();
		return str;
	}

	String getRemainder(StringTokenizer tk) {
		String str = "";
		if (tk.hasMoreTokens())
			str = tk.nextToken();
		while (tk.hasMoreTokens()) {
			str += " " + tk.nextToken();
		}
		return str;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

}
